package com.shop.cereshop.business.service.product.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.business.dao.dl.CereShopCartDao;
import com.shop.cereshop.business.dao.order.CereShopOrderDAO;
import com.shop.cereshop.business.dao.product.CereShopProductDAO;
import com.shop.cereshop.business.dl.logic.domain.CereShopCart;
import com.shop.cereshop.business.page.canvas.CanvasProduct;
import com.shop.cereshop.business.page.canvas.CanvasProductParam;
import com.shop.cereshop.business.page.canvas.CanvasShop;
import com.shop.cereshop.business.page.product.ShopProduct;
import com.shop.cereshop.business.page.product.Sku;
import com.shop.cereshop.business.param.product.*;
import com.shop.cereshop.business.redis.service.api.StringRedisService;
import com.shop.cereshop.business.service.checkImport.ImportCheckService;
import com.shop.cereshop.business.service.log.CerePlatformLogService;
import com.shop.cereshop.business.service.product.CereProductImageService;
import com.shop.cereshop.business.service.product.CereProductSkuService;
import com.shop.cereshop.business.service.product.CereShopProductService;
import com.shop.cereshop.business.service.product.CereSkuNameService;
import com.shop.cereshop.business.service.tool.CereShopCouponDetailService;
import com.shop.cereshop.business.service.tool.CereShopCouponService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.domain.business.CerePlatformBusiness;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.product.CereProductImage;
import com.shop.cereshop.commons.domain.product.CereProductSku;
import com.shop.cereshop.commons.domain.product.CereShopProduct;
import com.shop.cereshop.commons.domain.product.CereSkuName;
import com.shop.cereshop.commons.domain.tool.CereShopCoupon;
import com.shop.cereshop.commons.domain.tool.CereShopCouponDetail;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.poi.ImportExeclUtil;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.TimeUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class CereShopProductServiceImpl implements CereShopProductService {

    @Autowired
    private CereShopCartDao cereShopCartDao;

    @Autowired
    private CereShopProductDAO cereShopProductDAO;

    @Autowired
    private CereProductImageService cereProductImageService;

    @Autowired
    private CereProductSkuService cereProductSkuService;

    @Autowired
    private ImportCheckService importCheckService;

    @Autowired
    private CerePlatformLogService cerePlatformLogService;

    @Autowired
    private CereSkuNameService cereSkuNameService;

    @Autowired
    private CereShopOrderDAO cereShopOrderDAO;

    @Autowired
    private StringRedisService stringRedisService;

    @Autowired
    private CereShopCouponService cereShopCouponService;

    @Autowired
    private CereShopCouponDetailService cereShopCouponDetailService;

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void save(ProductSaveParam param, CerePlatformBusiness user) throws CoBusinessException {
        //w分佣比例
        Integer comm = param.getCommodityProportion();
        if (comm == null) {
            comm = 0;
        }
        if (comm < 0 || comm > 100) {
            throw new CoBusinessException(CoReturnFormat.TOBIG);
        }

        String valname = param.getNames().get(0).getValues().get(0).getSkuValue();
        if (valname.length() > 10) {
            throw new CoBusinessException(CoReturnFormat.SUPER_LONG);
        }
        if (param.getClassifyId() == 7) {
            BigDecimal valname2 = param.getSkus().get(0).getPrice();
            if (valname2.compareTo(new BigDecimal(0.1)) < 0) {
                throw new CoBusinessException(CoReturnFormat.LOWEST);
            }
            //w当新增积分商品的价格有2位小数时, 四舍五入,保留一位小数(因为积分和钱比率为10:1,这样可以保证积分不会有小数)
            valname2 = valname2.setScale(1, RoundingMode.HALF_UP);
            param.getSkus().get(0).setPrice(valname2);
        }

        String time = TimeUtils.yyMMddHHmmss();
        Long last = cereShopProductDAO.getLast();
        //新增商品数据
        CereShopProduct cereShopProduct = new CereShopProduct();
        cereShopProduct.setSort(last);
        cereShopProduct.setProductName(param.getProductName());
        cereShopProduct.setProductBrief(param.getProductBrief());
        if (param.getTouristRoute() != null) {
            cereShopProduct.setTouristRoute(param.getTouristRoute());
        }
        cereShopProduct.setProductText(param.getProductText());
        cereShopProduct.setClassifyId(param.getClassifyId());
        cereShopProduct.setShopGroupId(param.getShopGroupId());
        cereShopProduct.setSupplierId(param.getSupplierId());
        cereShopProduct.setSupplierName(param.getSupplierName());
        cereShopProduct.setProductNo(param.getProductNo());
        cereShopProduct.setFeeInclude(param.getFeeInclude());
        cereShopProduct.setFeeExclude(param.getFeeExclude());
        cereShopProduct.setGetTicketLocation(param.getGetTicketLocation());
        cereShopProduct.setOpenDate(param.getOpenDate());
        cereShopProduct.setIfLogistics(Integer.parseInt(param.getIfLogistics()));
        cereShopProduct.setIfOversold(Integer.parseInt(param.getIfOversold()));
        cereShopProduct.setShelveState(Integer.parseInt(param.getShelveState()));
        cereShopProduct.setCreateTime(time);
        cereShopProduct.setShopId(param.getShopId());
        cereShopProduct.setTouristRoute(param.getTouristRoute());
        cereShopProduct.setShareImage(param.getShareImage());
        if (param.getCommodityProportion() == null) {
            param.setCommodityProportion(0);
            cereShopProduct.setCommodityProportion(0);
        } else {
            cereShopProduct.setCommodityProportion(param.getCommodityProportion());
        }
        try {
            cereShopProductDAO.insert(cereShopProduct);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CoBusinessException(CoReturnFormat.DATA_TOO_LONG);
        }
        if (!EmptyUtils.isEmpty(param.getImages())) {
            List<CereProductImage> list = new ArrayList<>();
            //新增商品图片数据
            Stream.iterate(0, i -> i + 1).limit(param.getImages().size()).forEach(i -> {
                CereProductImage cereProductImage = new CereProductImage();
                cereProductImage.setProductId(cereShopProduct.getProductId());
                cereProductImage.setProductImage(param.getImages().get(i).getImgPath());
                cereProductImage.setSort(i + 1);
                list.add(cereProductImage);
            });
            cereProductImageService.insertBatch(list);
        }
        //封装规格名和规格值数据到map中
        Map<String, NameValue> map = new HashMap<>();
        param.getNames().forEach(a -> {
            a.getValues().forEach(value -> {
                NameValue nameValue = new NameValue();
                nameValue.setSkuName(a.getSkuName());
                nameValue.setSkuValue(value.getSkuValue());
                nameValue.setImage(value.getImage());
                if (a.getNeedImg()) {
                    nameValue.setNeed(IntegerEnum.YES.getCode());
                } else {
                    nameValue.setNeed(IntegerEnum.NO.getCode());
                }
                map.put(a.getCode() + "-" + value.getValueCode(), nameValue);
            });
        });

//        查询当前是否有全部商品且进行中状态的优惠券
        List<CereShopCoupon> coupons = cereShopCouponService.findAllByShopId(cereShopProduct.getShopId());
        if (!EmptyUtils.isEmpty(coupons)) {
            //如果有,将新增的商品插入到优惠券商品明细表中
            List<CereShopCouponDetail> details = coupons.stream().map(coupon -> {
                CereShopCouponDetail detail = new CereShopCouponDetail();
                detail.setProductId(cereShopProduct.getProductId());
                detail.setShopCouponId(coupon.getShopCouponId());
                return detail;
            }).collect(Collectors.toList());
            //批量插入数据
            cereShopCouponDetailService.insertBatch(details);
        }

//        新增规格数据
        saveSkus(param.getSkus(), cereShopProduct, null, time, map, param.getNames());
//        新增日志
//        cerePlatformLogService.addLog(user,"商品管理","商户端操作","添加商品",cereShopProduct.getProductId(),time);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void update(ProductUpdateParam param, CerePlatformBusiness user) throws CoBusinessException {
        //w从这里删除规格
        Long productId = param.getProductId();
        //w获取该商品存在的规格id
        List<Long> l1 = cereShopProductDAO.getSkuIds(productId);
        if (param.getSkus().size() <= l1.size()) {
            int l1Size = l1.size();
            for (int i = 0; i < l1Size; i++) {
                for (SkuParam s : param.getSkus()) {
                    Long skuId = s.getSkuId();
                    Long aLong = l1.get(i);
                    if (skuId.equals(aLong)) {
                        l1.remove(i);
                        l1Size--;
                        if (l1Size == 0) {
                            break;
                        }
                    }
                }
            }
            param.setDeletes(l1);
        }
        Integer comm = param.getCommodityProportion();
        if (comm < 0 || comm > 100) {
            throw new CoBusinessException(CoReturnFormat.TOBIG);
        }
        String valname = param.getNames().get(0).getValues().get(0).getSkuValue();
        if (valname.length() > 10) {
            throw new CoBusinessException(CoReturnFormat.SUPER_LONG);
        }
        //w当修改积分商品的价格有2位小数时, 四舍五入,保留一位小数(因为积分和钱比率为10:1,这样可以保证积分不会有小数)
        Long productId99 = param.getProductId();
        CereShopProduct product77 = cereShopProductDAO.selectByPrimaryKey(productId99);
        if (product77.getClassifyId() == 7) {
            BigDecimal valname2 = param.getSkus().get(0).getPrice();
            if (valname2.compareTo(new BigDecimal(0.1)) < 0) {
                throw new CoBusinessException(CoReturnFormat.LOWEST);
            }
            valname2 = valname2.setScale(1, RoundingMode.HALF_UP);
            param.getSkus().get(0).setPrice(valname2);
        }
        String time = TimeUtils.yyMMddHHmmss();
        //更新商品数据
        CereShopProduct cereShopProduct = new CereShopProduct();
        cereShopProduct.setProductId(param.getProductId());
        cereShopProduct.setProductName(param.getProductName());
        cereShopProduct.setProductBrief(param.getProductBrief());
        cereShopProduct.setProductText(param.getProductText());
        cereShopProduct.setClassifyId(param.getClassifyId());
        cereShopProduct.setShopGroupId(param.getShopGroupId());
        cereShopProduct.setSupplierId(param.getSupplierId());
        cereShopProduct.setSupplierName(param.getSupplierName());
        cereShopProduct.setIfLogistics(param.getIfLogistics());
        cereShopProduct.setIfOversold(param.getIfOversold());
        cereShopProduct.setShelveState(param.getShelveState());
        cereShopProduct.setUpdateTime(time);
        cereShopProduct.setShopId(param.getShopId());
        cereShopProduct.setTouristRoute(param.getTouristRoute());
        cereShopProduct.setPurchaseNotes(param.getPurchaseNotes());
        cereShopProduct.setCommodityProportion(param.getCommodityProportion());
        cereShopProduct.setShareImage(param.getShareImage());
        cereShopProductDAO.updateByPrimaryKeySelective(cereShopProduct);


        if (!EmptyUtils.isEmpty(param.getImages())) {
            //清空商品图片
            cereProductImageService.deleteByProductId(param.getProductId());
            List<CereProductImage> list = new ArrayList<>();
            //新增商品图片数据
            Stream.iterate(0, i -> i + 1).limit(param.getImages().size()).forEach(i -> {
                CereProductImage cereProductImage = new CereProductImage();
                cereProductImage.setProductId(cereShopProduct.getProductId());
                cereProductImage.setProductImage(param.getImages().get(i).getImgPath());
                cereProductImage.setSort(i + 1);
                list.add(cereProductImage);
            });
            cereProductImageService.insertBatch(list);
        }
        //封装规格名和规格值数据到map中
        Map<String, NameValue> map = new HashMap<>();
        param.getNames().forEach(a -> {
            a.getValues().forEach(value -> {
                NameValue nameValue = new NameValue();
                nameValue.setSkuName(a.getSkuName());
                nameValue.setSkuValue(value.getSkuValue());
                nameValue.setImage(value.getImage());
                if (a.getNeedImg()) {
                    nameValue.setNeed(IntegerEnum.YES.getCode());
                } else {
                    nameValue.setNeed(IntegerEnum.NO.getCode());
                }
                map.put(a.getCode() + "-" + value.getValueCode(), nameValue);
            });
        });
        //更新规格数据
        saveSkus(param.getSkus(), cereShopProduct, param.getDeletes(), time, map, param.getNames());
        //新增日志
        cerePlatformLogService.addLog(user, "商品管理", "商户端操作", "修改商品", cereShopProduct.getProductId(), time);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void delete(ProductDeleteParam param, CerePlatformBusiness user) throws CoBusinessException {
        int state = cereShopOrderDAO.selectByState(param.getProductId());
        if (state > 0) {
            throw new CoBusinessException(CoReturnFormat.UNPAID);
        }

        //校验商品是否参与正在进行的活动
        Long productId = cereShopProductDAO.checkActivity(param.getProductId());
        if (EmptyUtils.isLongEmpty(productId)) {
            productId = cereShopProductDAO.checkGroupWork(param.getProductId());
            if (EmptyUtils.isLongEmpty(productId)) {
                productId = cereShopProductDAO.checkSeckill(param.getProductId());
                if (EmptyUtils.isLongEmpty(productId)) {
                    productId = cereShopProductDAO.checkDiscount(param.getProductId());
                    if (!EmptyUtils.isLongEmpty(productId)) {
                        throw new CoBusinessException(CoReturnFormat.PRODUCT_WITH_ACTIVITY);
                    }
                } else {
                    throw new CoBusinessException(CoReturnFormat.PRODUCT_WITH_ACTIVITY);
                }
            } else {
                throw new CoBusinessException(CoReturnFormat.PRODUCT_WITH_ACTIVITY);
            }
        } else {
            throw new CoBusinessException(CoReturnFormat.PRODUCT_WITH_ACTIVITY);
        }
        String time = TimeUtils.yyMMddHHmmss();
        //删除商品数据
        cereShopProductDAO.deleteByPrimaryKey(param.getProductId());
        //删除规格属性数据
        cereSkuNameService.deleteByProductId(param.getProductId());
        //删除规格数据
        cereProductSkuService.deleteByProductId(param.getProductId());
        //删除商品图片数据
        cereProductImageService.deleteByProductId(param.getProductId());
        //新增日志
//        cerePlatformLogService.addLog(user,"商品管理","商户端操作","删除商品",param.getProductId(),time);
    }

    @Override
    public ShopProduct getById(Long productId) throws CoBusinessException {
        //查询商品信息
        ShopProduct shopProduct = cereShopProductDAO.getById(productId);
        if (shopProduct.getCommodityProportion() == null) {
            shopProduct.setCommodityProportion(0);
        }
        //查询商品图片信息
        List<String> images = cereProductImageService.findByProductId(productId);
        //查询规格信息
        List<Sku> skus = cereProductSkuService.findByProductId(productId);
        //查询规格名数据
        List<SkuNameParam> names = cereSkuNameService.findNameByProductId(productId);
        if (!EmptyUtils.isEmpty(names)) {
            if (!EmptyUtils.isEmpty(names.get(0).getSkuName())) {
                //多款式
                names.forEach(a -> a.setValues(cereSkuNameService.findByName(a.getSkuName(), productId)));
            } else {
                //单款式,查询规格值数据
                CereSkuName value = cereSkuNameService.findValueByProductId(productId);
                if (value != null) {
                    List<SkuValueParam> values = new ArrayList<>();
                    SkuValueParam skuValueParam = new SkuValueParam();
                    skuValueParam.setValueCode(value.getValueCode());
                    skuValueParam.setSkuValue(value.getSkuValue());
                    skuValueParam.setImage(value.getImage());
                    values.add(skuValueParam);
                    names.get(0).setValues(values);
                }
            }
        }
        //封装规格里面的规格名和值级别数据
        skus.forEach(sku -> sku.setSkuAttrCodeDTOList(cereSkuNameService.findBySkuId(sku.getSkuId())));
        shopProduct.setImages(EmptyUtils.getImages(images));
        shopProduct.setSkus(skus);
        shopProduct.setNames(names);
        return shopProduct;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void start(ProductUpDownParam param, CerePlatformBusiness user) throws CoBusinessException {
        String time = TimeUtils.yyMMddHHmmss();
        CereShopProduct cereShopProduct = new CereShopProduct();
        cereShopProduct.setProductId(param.getProductId());
        cereShopProduct.setShelveState(param.getShelveState());
        cereShopProductDAO.updateByPrimaryKeySelective(cereShopProduct);
        //w商品下架, 顺便删除其他人购物车列表存在的该商品
        cereShopProductDAO.delByproId(cereShopProduct.getProductId());
        String describe = "";
        if (IntegerEnum.YES.getCode().equals(param.getShelveState())) {
            describe = "上架商品";
        } else {
            describe = "下架商品";
        }
        //新增日志
        cerePlatformLogService.addLog(user, "商品管理", "商户端操作", describe, cereShopProduct.getProductId(), time);
    }

    @Override
    public Page getAll(ProductGetAllParam param) throws CoBusinessException {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<ShopProduct> list = cereShopProductDAO.getAll(param);
        if (!EmptyUtils.isEmpty(list)) {
            list.forEach((shopProduct -> {
                if (!EmptyUtils.isEmpty(shopProduct.getSkuImage())) {
                    //规格配图了,取规格图片展示
                    shopProduct.setProductImage(shopProduct.getSkuImage());
                }
                if (shopProduct.getCommodityProportion() == null) {
                    shopProduct.setCommodityProportion(0);
                }
                //查询规格商品销量
                Integer total = cereProductSkuService.findVolumeByProductId(shopProduct.getProductId());
                shopProduct.setVolume(total);
            }));
        }
        PageInfo<ShopProduct> pageInfo = new PageInfo<>(list);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }

    @Override
    public void importProduct(Workbook wb) throws CoBusinessException, Exception {
        List<ProductImport> list = ImportExeclUtil.readDateListT(wb, new ProductImport());
        String time = TimeUtils.yyMMddHHmmss();
        //校验有效数据
        List<ProductSaveParam> products = importCheckService.checkProduct(list);
        if (!EmptyUtils.isEmpty(products)) {
            List<CereSkuName> skuNames = new ArrayList<>();
            for (ProductSaveParam param : products) {
                //新增商品数据
                CereShopProduct cereShopProduct = new CereShopProduct();
                cereShopProduct.setProductName(param.getProductName());
                cereShopProduct.setClassifyId(param.getClassifyId());
                cereShopProduct.setSupplierName(param.getSupplierName());
                cereShopProduct.setIfLogistics(Integer.parseInt(param.getIfLogistics()));
                cereShopProduct.setIfOversold(Integer.parseInt(param.getIfOversold()));
                cereShopProduct.setShelveState(Integer.parseInt(param.getShelveState()));
                cereShopProduct.setCreateTime(time);
                cereShopProduct.setShopId(param.getShopId());
                cereShopProductDAO.insert(cereShopProduct);
                //查询当前是否有全部商品且进行中状态的优惠券
                List<CereShopCoupon> coupons = cereShopCouponService.findAllByShopId(cereShopProduct.getShopId());
                if (!EmptyUtils.isEmpty(coupons)) {
                    //如果有,将新增的商品插入到优惠券商品明细表中
                    List<CereShopCouponDetail> details = coupons.stream().map(coupon -> {
                        CereShopCouponDetail detail = new CereShopCouponDetail();
                        detail.setProductId(cereShopProduct.getProductId());
                        detail.setShopCouponId(coupon.getShopCouponId());
                        return detail;
                    }).collect(Collectors.toList());
                    //批量插入数据
                    cereShopCouponDetailService.insertBatch(details);
                }
                //新增规格数据
                saveExcelSkus(param.getSkus(), cereShopProduct.getProductId(), skuNames, time);
            }
            cereSkuNameService.insertBatch(skuNames);
        }
    }

    @Override
    public CereShopProduct checkName(Long shopId, Long classifyId, String productName) {
        return cereShopProductDAO.checkName(shopId, classifyId, productName);
    }

    @Override
    public Page getProducts(CanvasProductParam param) throws CoBusinessException {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<CanvasProduct> list = cereShopProductDAO.getProducts(param);
        PageInfo<CanvasProduct> pageInfo = new PageInfo<>(list);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }

    @Override
    public Page getShops(CanvasProductParam param) throws CoBusinessException {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<CanvasShop> list = cereShopProductDAO.getShops(param);
        PageInfo<CanvasShop> pageInfo = new PageInfo<>(list);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }

    @Override
    public List<Long> findAllZeroStockNumber() {
        return cereShopProductDAO.findAllZeroStockNumber();
    }

    @Override
    public void updateBatchShelveState(List<Long> ids, String time) throws CoBusinessException {
        cereShopProductDAO.updateBatchShelveState(ids, time);
    }

    @Override
    public CereShopProduct selectById(Integer productId) {
        return cereShopProductDAO.selectByPrimaryKey(Long.valueOf(productId));
    }

    @Override
    public void setRecommende(Integer recommendedMark, Integer productId) {
        cereShopProductDAO.setRecommende(recommendedMark, productId);
    }

    @Override
    public void setRecommende2(Integer productId, Integer sort) {
        cereShopProductDAO.setRecommende2(productId, sort);
    }

    @Override
    public void setRecommende3(Integer productId, Integer commodityProportion) {
        cereShopProductDAO.setRecommende3(productId, commodityProportion);
    }

    @Override
    public void deleteByProductID(Long productId) {
        cereShopProductDAO.deleteByProductID(productId);
    }


    private void saveExcelSkus(List<SkuParam> skus, Long productId, List<CereSkuName> skuNames, String time) throws CoBusinessException {
        if (!EmptyUtils.isEmpty(skus)) {
            for (SkuParam sku : skus) {
                CereProductSku cereProductSku = new CereProductSku();
                cereProductSku.setStyle(IntegerEnum.SKU_STYLE_ONE.getCode());
                cereProductSku.setOriginalPrice(sku.getOriginalPrice());
                cereProductSku.setPrice(sku.getPrice());
                cereProductSku.setSkuImage(sku.getSkuImage());
                cereProductSku.setSKU(sku.getSku());
                cereProductSku.setStockNumber(sku.getStockNumber());
                cereProductSku.setWeight(sku.getWeight());
                cereProductSku.setProductId(productId);
                cereProductSku.setCreateTime(time);
                //新增规格
                cereProductSkuService.insert(cereProductSku);
                //将商品库存数量放到redis中
                stringRedisService.set(String.valueOf(cereProductSku.getSkuId()), cereProductSku.getStockNumber());
                //同步新增规格名和规格值关联数据
                CereSkuName cereSkuName = new CereSkuName();
                cereSkuName.setSkuValue(sku.getNameValue().getSkuValue());
                cereSkuName.setSkuId(cereProductSku.getSkuId());
                cereSkuName.setNameCode("attr_code_0");
                cereSkuName.setValueCode("attr_code_0_value_0");
                skuNames.add(cereSkuName);
            }
        }
    }

    private void saveSkus(List<SkuParam> skus, CereShopProduct cereShopProduct, List<Long> deletes,
                          String time, Map<String, NameValue> map, List<SkuNameParam> names) throws CoBusinessException {
        if (!EmptyUtils.isEmpty(skus)) {
            for (SkuParam sku : skus) {
                CereProductSku cereProductSku = new CereProductSku();
                cereProductSku.setSkuId(sku.getSkuId());
                cereProductSku.setOriginalPrice(sku.getOriginalPrice());
                cereProductSku.setPrice(sku.getPrice());
                cereProductSku.setSkuImage(sku.getSkuImage());
                cereProductSku.setSKU(sku.getSku());
                cereProductSku.setStockNumber(sku.getStockNumber());
                cereProductSku.setTotal(sku.getTotal());
                cereProductSku.setStyle(sku.getStyle());
                cereProductSku.setWeight(sku.getWeight());
                if (EmptyUtils.isEmpty(sku.getSkuId())) {
                    cereProductSku.setProductId(cereShopProduct.getProductId());
                    cereProductSku.setCreateTime(time);
                    //新增规格
                    cereProductSkuService.insert(cereProductSku);
                    //将商品库存数量放到redis中
                    stringRedisService.set(String.valueOf(cereProductSku.getSkuId()), cereProductSku.getStockNumber());
                    //同步新增规格名和规格值关联数据
                    if (IntegerEnum.SKU_STYLE_ONE.getCode().equals(cereProductSku.getStyle())) {
                        //如果是单款式
                        CereSkuName cereSkuName = new CereSkuName();
                        cereSkuName.setSkuValue(names.get(0).getValues().get(0).getSkuValue());
                        cereSkuName.setSkuId(cereProductSku.getSkuId());
                        cereSkuName.setNeed(IntegerEnum.NO.getCode());
                        cereSkuNameService.insert(cereSkuName);
                    } else {
                        //多款式
                        if (!EmptyUtils.isEmpty(sku.getSkuAttrCodeDTOList())) {
                            List<CereSkuName> collect = sku.getSkuAttrCodeDTOList().stream()
                                    .map(a -> {
                                        CereSkuName cereSkuName = new CereSkuName();
                                        NameValue nameValue = map.get(a.getCode() + "-" + a.getValueCode());
                                        if (nameValue != null) {
                                            cereSkuName.setSkuValue(nameValue.getSkuValue());
                                            cereSkuName.setSkuName(nameValue.getSkuName());
                                            cereSkuName.setImage(nameValue.getImage());
                                            cereSkuName.setSkuId(cereProductSku.getSkuId());
                                            cereSkuName.setNameCode(a.getCode());
                                            cereSkuName.setValueCode(a.getValueCode());
                                            cereSkuName.setNeed(nameValue.getNeed());
                                            return cereSkuName;
                                        } else {
                                            return null;
                                        }
                                    })
                                    //过滤空对象
                                    .filter(Objects::nonNull)
                                    .collect(Collectors.toList());
                            if (!EmptyUtils.isEmpty(collect)) {
                                //判断规格名称长度
                                for (CereSkuName skuName : collect) {
                                    if (skuName.getSkuValue().length() > 9) {
                                        throw new CoBusinessException(CoReturnFormat.SPECIFICATION_NAME_LENGTH);
                                    }
                                }
                                cereSkuNameService.insertBatch(collect);
                            }
                        }
                    }
                } else {
                    //查询规格原有库存数量
                    int stockNumber = cereProductSkuService.findStockNumber(cereProductSku.getSkuId());
                    //获取redis中库存数量
                    int redis = 0;
                    if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(cereProductSku.getSkuId())))) {
                        redis = (int) stringRedisService.get(String.valueOf(cereProductSku.getSkuId()));
                    } else {
                        redis = stockNumber;
                    }
                    //计算库存差值=修改后的库存-原有库存
                    int number = cereProductSku.getStockNumber() - stockNumber;
                    //将商品库存数量放到redis中
                    stringRedisService.set(String.valueOf(cereProductSku.getSkuId()), number + redis);
                    //更新规格
                    cereProductSku.setUpdateTime(time);
                    cereProductSkuService.update(cereProductSku);

                    //清空规格属性数据
                    cereSkuNameService.deleteBySkuId(cereProductSku.getSkuId());
                    if (IntegerEnum.SKU_STYLE_ONE.getCode().equals(cereProductSku.getStyle())) {
                        //单款式
                        CereSkuName cereSkuName = new CereSkuName();
                        cereSkuName.setSkuValue(names.get(0).getValues().get(0).getSkuValue());
                        cereSkuName.setSkuId(cereProductSku.getSkuId());
                        cereSkuName.setNeed(IntegerEnum.NO.getCode());
                        cereSkuNameService.insert(cereSkuName);
                    } else {
                        //多款式
                        if (!EmptyUtils.isEmpty(sku.getSkuAttrCodeDTOList())) {
                            List<CereSkuName> collect = sku.getSkuAttrCodeDTOList().stream()
                                    .map(a -> {
                                        CereSkuName cereSkuName = new CereSkuName();
                                        NameValue nameValue = map.get(a.getCode() + "-" + a.getValueCode());
                                        if (nameValue != null) {
                                            cereSkuName.setSkuValue(nameValue.getSkuValue());
                                            cereSkuName.setSkuName(nameValue.getSkuName());
                                            cereSkuName.setImage(nameValue.getImage());
                                            cereSkuName.setSkuId(cereProductSku.getSkuId());
                                            cereSkuName.setNameCode(a.getCode());
                                            cereSkuName.setValueCode(a.getValueCode());
                                            cereSkuName.setNeed(nameValue.getNeed());
                                            return cereSkuName;
                                        } else {
                                            return null;
                                        }
                                    })
                                    //过滤空对象
                                    .filter(Objects::nonNull)
                                    .collect(Collectors.toList());
                            if (!EmptyUtils.isEmpty(collect)) {
                                //批量插入规格数据
                                cereSkuNameService.insertBatch(collect);
                            }
                        }
                    }

                    //修改购物车中该规格值
                    CereShopCart cereShopCart = new CereShopCart();
                    cereShopCart.setSkuId(sku.getSkuId());
                    cereShopCart.setProductPrice(sku.getPrice());
                    cereShopCart.setProductName(cereShopProduct.getProductName());
                    cereShopCartDao.updateByPrimaryKeySelective(cereShopCart);


                }

            }
        }
        if (!EmptyUtils.isEmpty(deletes)) {
            //删除规格
            cereProductSkuService.deleteByIds(deletes);
            //清空规格名和规格值关联数据
            cereSkuNameService.deleteByIds(deletes);
        }
    }
}
